package repositories

import (
	"context"
	"errors"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	mymongo "imooc-product/mongo"
	"imooc-product/datamodels"
)

//第一步，先开发对应的接口
//第二步，实现定义的接口
type IProduct interface {
	//连接数据库
	Conn()(error)
	//插入数据库
	Insert(*datamodels.Product)(interface{},error)
	//删除数据库
	Delete(primitive.ObjectID)bool
	//修改数据库
	Update(*datamodels.Product)error
	//查数据库
	SelectByKey(primitive.ObjectID)(*datamodels.Product,error)
	//查找所有
	SelectAll()([]*datamodels.Product,error)
}

type ProductManager struct {
	table string
	mongodbDatabase mymongo.Database
}

func NewProductManager(table string,mongo *mymongo.Database)IProduct  {
	return &ProductManager{table: table,mongodbDatabase: *mongo}
}

//数据库连接
func (p *ProductManager)Conn()(err error)  {
	if p.mongodbDatabase == nil{
		mongodb,err := mymongo.Get()
		if err != nil{
			return err
		}
		p.mongodbDatabase = mongodb
	}
	if p.table == ""{
		p.table = "product"
	}
	return
}

//插入
func (p *ProductManager)Insert(product *datamodels.Product)(productID interface{},err error)  {
	//判断连接是否存在
	if err = p.Conn(); err != nil{
		return
	}
	//插入
	insertresult,err := p.mongodbDatabase.Collection("product").InsertOne(context.TODO(),*product)
	if err != nil{
		return 0,err
	}
	return insertresult.InsertedID,nil
}
//删除
func (p *ProductManager)Delete(id primitive.ObjectID)(result bool)  {
	//判断连接是否存在
	if err := p.Conn();err != nil{
		return
	}
	//删除
	deleteresult,err := p.mongodbDatabase.Collection("product").DeleteOne(context.TODO(),bson.M{"_id":id})
	if err != nil{
		return
	}
	if deleteresult.DeletedCount > 0{
		return true
	}
	return
}

//修改数据库
func (p *ProductManager)Update(product *datamodels.Product)(result error)  {
	//判断连接是否存在
	if err := p.Conn();err != nil{
		return
	}
	//更新
	uploadresult,err :=  p.mongodbDatabase.Collection("product").UpdateOne(context.TODO(),bson.M{"_id": product.ID},*product)
	if err != nil{
		return err
	}
	if uploadresult.UpsertedCount > 0{
		return
	}
	return
}
//查找数据库
func (p *ProductManager)SelectByKey(productid primitive.ObjectID)(*datamodels.Product,error)  {
	//判断连接是否存在
	if err := p.Conn();err != nil{
		return nil, err
	}
	//查找
	var resultdata datamodels.Product
	p.mongodbDatabase.Collection("product").FindOne(context.TODO(),bson.M{"_id":productid}).Decode(&resultdata)
	if resultdata.ProductImage != ""{
		return &resultdata,nil
	}
	return nil,errors.New("查找数据库失败")
}
//查找所有
func (p *ProductManager)SelectAll()(productlist []*datamodels.Product,err error){
	//判断连接是否存在
	if err := p.Conn();err !=nil{
		return productlist,err
	}
	//查找所有
	cur,err :=  p.mongodbDatabase.Collection("product").Find(context.TODO(),bson.M{})
	if err != nil{
		return productlist,err
	}
	var resultlist []*datamodels.Product
	for cur.Next(context.TODO()){
		//创建一个值，将单个文件解码为该值
		var elem datamodels.Product
		err := cur.Decode(&elem)
		if err != nil{
			return productlist,err
		}
		resultlist = append(resultlist,&elem)
	}
	return resultlist,nil
}
